<template>
  <div>
    {{ isNew ? '新增' : '修改' }}课程
    <ele-form
      v-model="data"
      :form-desc="formDesc"
      :rules="rules"
      :request-fn="handleSubmit"
    ></ele-form>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
@Component({})
export default class CourseEdit extends Vue {
  @Prop({ type: String }) id?: string

  data = {}
  formDesc = {
    name: {
      type: 'input',
      label: '课程名称'
    },
    coverImg: {
      type: 'input',
      label: '课程封面图'
    }
  }

  rules = {
    name: { required: true, type: 'string', message: '必须填写名称' },
    coverImg: { required: true, message: '必须填写封面图地址' }
  }

  get isNew () {
    return !this.id
  }

  async handleSubmit () {
    const url = !this.id ? 'courses' : `courses/${this.id}`
    const method = !this.id ? 'post' : 'put'

    await this.$http[method](url, this.data)
    this.$message.success('提交成功')
    this.data = {}
    this.$router.go(-1)
  }

  async fetch () {
    const result = await this.$http.get(`/courses/${this.id}`)

    this.data = result.data
  }

  created () {
    this.id && this.fetch()
  }
}
</script>
